import { ref, computed } from 'vue'

export interface UsePaginationOptions {
    pageSize?: number
    initialPage?: number
}

export function usePagination<T>(
    items: import('vue').Ref<T[]>,
    options: UsePaginationOptions = {}
) {
    const { pageSize = 10, initialPage = 1 } = options

    const currentPage = ref(initialPage)

    // 计算总页数
    const totalPages = computed(() => {
        return Math.ceil(items.value.length / pageSize) || 1
    })

    // 计算当前页的数据
    const paginatedItems = computed(() => {
        const start = (currentPage.value - 1) * pageSize
        const end = start + pageSize
        return items.value.slice(start, end)
    })

    // 计算分页信息
    const pageInfo = computed(() => {
        const total = items.value.length
        const start = total === 0 ? 0 : (currentPage.value - 1) * pageSize + 1
        const end = Math.min(currentPage.value * pageSize, total)

        return {
            start,
            end,
            total,
            currentPage: currentPage.value,
            totalPages: totalPages.value,
            pageSize
        }
    })

    // 跳转到指定页
    const goToPage = (page: number) => {
        const pageNum = Math.max(1, Math.min(page, totalPages.value))
        currentPage.value = pageNum
    }

    // 下一页
    const nextPage = () => {
        if (currentPage.value < totalPages.value) {
            currentPage.value++
        }
    }

    // 上一页
    const prevPage = () => {
        if (currentPage.value > 1) {
            currentPage.value--
        }
    }

    // 是否是第一页
    const isFirstPage = computed(() => currentPage.value === 1)

    // 是否是最后一页
    const isLastPage = computed(() => currentPage.value === totalPages.value)

    // 重置到第一页
    const reset = () => {
        currentPage.value = 1
    }

    // 当数据改变时，自动检查当前页是否有效
    const validateCurrentPage = () => {
        if (currentPage.value > totalPages.value) {
            currentPage.value = Math.max(1, totalPages.value)
        }
    }

    return {
        currentPage,
        totalPages,
        paginatedItems,
        pageInfo,
        goToPage,
        nextPage,
        prevPage,
        isFirstPage,
        isLastPage,
        reset,
        validateCurrentPage
    }
}
